<template>
  <div>
    <h1>新建分区</h1>
    <!-- model绑定表单模型 rules绑定表单验证规则 ref返回表单 -->
    <el-form
      :model="model"
      :rules="rules"
      ref="ruleForm"
      @submit.native.prevent
    >
      <!-- prop 接受子组件 name值  validate-event绑定提交时验证-->
      <el-form-item prop="name" label="专区名称">
        <el-input
          :validate-event="false"
          placeholder="输入专区名"
          v-model="model.name"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 提交时传入表单 -->
        <el-button
          type="primary"
          native-type="submit"
          @click="save('ruleForm')"
        >
          <span>保存</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style></style>
<script>
export default {
  data() {
    return {
      model: {
        name: "",
      },
      rules: {
        // 表单验证规则
        name: [
          { required: true, message: "请输入活动名称" }, // 'blur'是鼠标失去焦点的时候会触发验证，required 不能为空
        ],
      },
    }
  },
  methods: {
    save(formName) {
      // validate 验证表单返回值
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //发送数据库创建post请求
          const res = await this.$http.post("categories", this.model)
          // 判断分区是否已存在
          
          if (res.data.name != "MongoError") {
            //创建完成 跳转至专区列表
            this.$router.push("/categories/list")
            //创建消息提醒
            this.$notify({
              title: "成功",
              position: "top-left",
              type: "success",
              message: "分区保存成功！",
            })
          } else {
            this.$notify({
              title: "警告",
              position: "top-left",
              type: "warning",
              message: "分区已存在！",
            })
          }
        }
      })
    },
  },
}
</script>
